package com.jc.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JWTDemo {
    public static void main(String[] args) {

        parseToken(createToken());


    }

    /**
     * 解析token
     * @param token
     */
    private static void parseToken(String token) {
        Claims parser = Jwts.parser().setSigningKey("mycat666")
                .parseClaimsJws(token)
                .getBody();

        String id = parser.getId();
        System.out.println("id: " + id);
        String subject = parser.getSubject();
        System.out.println("subject: " + subject);
        Date issuedAt = parser.getIssuedAt();
        System.out.println("issuedAt: " + issuedAt);
        Date expiration = parser.getExpiration();
        System.out.println("expiration: " + expiration);
        Object role = parser.get("role");
        System.out.println("role: " + role);
    }

    /**
     * 生成token
     * @return
     */
    private static String createToken() {
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId("123")//id
                .setSubject("tom")//用户名
                .setIssuedAt(new Date())//生成时间
                .setExpiration(new Date(new Date().getTime() + 60000))//过期时间
                .claim("role", "student")//自定义paylaod
                .signWith(SignatureAlgorithm.HS256, "mycat666");
        String token = jwtBuilder.compact();
        System.out.println(token);
        return token;
    }
}
